package com.example.yingjiguanli_demo.controller;

import com.example.yingjiguanli_demo.service.IMatchesService;
import com.example.yingjiguanli_demo.utils.MapUtil;
import com.example.yingjiguanli_demo.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author scj
 * @since 2024-11-15
 */
@RestController
@RequestMapping("/api/match")
public class MatchesController {

    @Autowired
    private IMatchesService matchService;

    @Autowired
    private UserUtils userUtils;

    @GetMapping("/find")
    public ResponseEntity<?> findMatch(@CookieValue(name = "SESSIONID", required = false) String sessionId) {
        if (sessionId == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("用户还未登陆");
        }

        Long userId = (long) userUtils.getUserId(sessionId);
        String opponentId = matchService.matchUser(userId);

        if (opponentId != null) {
            Map<String, String> response = MapUtil.of("status", "success", "opponentId", opponentId);
            return ResponseEntity.ok().body(response);
        } else {
            Map<String, String> response = MapUtil.of("status", "waiting", "message", "等待匹配中...");
            return ResponseEntity.ok().body(response);
        }
    }
}
